package webservice.restful;

import java.io.StringWriter;
import javax.ejb.EJB;
import javax.ws.rs.PathParam;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.json.XML;
import session.stateful.GrouponSessionBean;
import util.helper.IssuedGrouponList;
import util.helper.PurchasedGrouponList;

@Path("grouponJsonWebService")
public class GrouponJsonWebService {

    @EJB
    GrouponSessionBean grouponSessionBean;

    public GrouponJsonWebService() {
    }

    /*
     * Purpose: Input is the tourist id, and return back to the mobile list of purchased groupons
     * of this tourist
     */
    @GET
    @Produces("application/json")
    public String getPurchasedGrouponListJson(@PathParam("touristId") String touristId) {
        String jsonString = "";

        try {
            PurchasedGrouponList list = new PurchasedGrouponList();
            list.setPurchasedGrouponList(grouponSessionBean.getPurchasedGrouponByTouristId(Long.valueOf(touristId)));

            JAXBContext jc = JAXBContext.newInstance(PurchasedGrouponList.class);
            Marshaller marshaller = jc.createMarshaller();
            StringWriter writer = new StringWriter();
            marshaller.marshal(list, writer);

            String xmlString = writer.toString();

            jsonString = XML.toJSONObject(xmlString).toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return jsonString;
    }

    /*
     * Input is id of purchased groupon id and output is the list of available issued groupons
     * for this purchased groupon
     */
    @GET
    @Produces("application/json")
    public String getAvailGrouponListJson(@PathParam("purchasedGrouponId") String purchasedGrouponId) {
        String jsonString = "";

        try {
            IssuedGrouponList list = new IssuedGrouponList();
            list.setIssuedGrouponList(grouponSessionBean.getAvailIssuedGrouponByPurchasedGrouponId(Long.valueOf(purchasedGrouponId)));

            JAXBContext jc = JAXBContext.newInstance(IssuedGrouponList.class);
            Marshaller marshaller = jc.createMarshaller();
            StringWriter writer = new StringWriter();
            marshaller.marshal(list, writer);

            String xmlString = writer.toString();

            jsonString = XML.toJSONObject(xmlString).toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return jsonString;
    }
}
